package com.wangzhen.spring.ioc.dependcy.exception;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import javax.annotation.PostConstruct;
import java.lang.annotation.Annotation;

/**
 * bean创建异常演示示例
 */
public class BeanCreationExceptionDemo {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(BeanCreationExceptionDemo.class);
        // 手工注册bean，演示bean在创建过程中 的生命周期内 发生异常的场景
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(Foo.class);
        AbstractBeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();
        context.registerBeanDefinition("foo", beanDefinition);

        context.refresh();
        context.close();
    }

    static class Foo implements InitializingBean {

        @PostConstruct
        public void postConstruct() throws Exception{
            throw new Exception("postConstruct 发生异常了");
        }
        @Override
        public void afterPropertiesSet() throws Exception {
            throw new Exception("afterPropertiesSet 发生异常了！");
        }
    }

}
